package com.core.initialize;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.Attribute;

import java.util.List;

import org.apache.log4j.Logger;

import com.core.NetChannel;
import com.core.ServerAttributeKey;
import com.core.interfaces.IMessageManager;
import com.google.protobuf.MessageLite;

/**
 * 二进制转成mymessage
 * @author King
 *
 */
public class BytesToMessageDecode extends ByteToMessageDecoder
{
	private static final Logger log =Logger.getLogger(BytesToMessageDecode.class);
	
	private IMessageManager messageManager;
	
	
	public void setMessageManager(IMessageManager messageManager)
	{
		this.messageManager = messageManager;
	}
	
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf msg,
			List<Object> out) throws Exception 
	{
		try {
			if(!msg.isReadable())
				return;
			Channel channel = ctx.channel();
			final Message myMsg = new Message();
			int lenth = msg.readInt();
			myMsg.setModule(msg.readShort());
			myMsg.setAction(msg.readShort());
			//错误了直接把channel关闭
			if (lenth >=Integer.MAX_VALUE) {
				log.error("解析字节码太长，长度:"+lenth+"modelId"+myMsg.getModule()+"action"+myMsg.getAction());
				channel.close();
//			in.position(in.limit());
//			return true;
			}
			int bodyLenth = lenth - Message.CLIENTMIN_LENGTH;
			myMsg.setEncrypt(msg.readByte());
			Attribute<NetChannel> attr = channel.attr(ServerAttributeKey.netChannel);
			if(attr!=null)
			{
				myMsg.setChannel(attr.get());
			}
			if(bodyLenth!=0)
			{
				byte[] bytes = new byte[bodyLenth];
				msg.readBytes(bytes);
				MessageLite lite = messageManager.getMessage(myMsg.getModule(), myMsg.getAction());
				if(lite!=null)
				{
					myMsg.setBody(lite.newBuilderForType().mergeFrom(bytes).build());
					
				}else
					log.error("没有获得对应的消息体moduleId:"+myMsg.getModule()+"actionId:"+myMsg.getAction());
			}
			msg=null;
			out.add(myMsg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
